package w83b.w83bOperacionesPaso.w83bCertificaciones;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import w83b.w83bBeans.W83bCertificacionesBean;
import w83b.w83bBeans.W83bPlantillasBean;
import w83b.w83bBeans.W83bUsuarioXLNetsBean;
import w83b.w83bUtilidades.W83bUtilidadesComunes;
import w83b.w83bUtilidades.W83bUtilidadesRTF;
import w83b.w83bUtilidadesComunes.W83bClsConstantes;
import w83b.w83bUtilidadesComunes.W83bDateUtil;
import es.ejie.frmk.infraestructura.internacionalizacion.Q70GestorMensajesi18n;
import es.ejie.frmk.presentacion.operacion.paso.Q70ActionPasoOP;
import es.ejie.frmk.presentacion.sesiondatos.Q70ContextoEJIE;

// TODO: Auto-generated Javadoc
/**
 * The Class W83bTablaConveniosOP.java.
 *
 * @author Deusto Sistemas
 */
public class W83bTablaCertificacionesSindSectorRtfAction extends Q70ActionPasoOP{


	
	protected void processOP(Q70ContextoEJIE contexto, ActionErrors errores, ActionMapping mapping,
			ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		
	}

	protected ActionForward processForward(Q70ContextoEJIE contexto, ActionErrors errors, ActionMapping mapping, 
			ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

		//String strRutaRtf = Q70ListenerUtils.getApplicationProperty("RUTA_PLANTILLAS_RTF")+"plantillaCertSindSectNegCol.rtf";
		
		HashMap mapaPar = new HashMap();
		HashMap plantillas=(HashMap)contexto.get("w83bPlantillasMap");
		W83bPlantillasBean plantilla=(W83bPlantillasBean)plantillas.get(W83bClsConstantes.CERTIFICADO_REPRESENTACIÓN_SINDICAL_SECTORES_NEGOCIACION_COLECTIVA.toUpperCase());
		W83bCertificacionesBean certificacion=(W83bCertificacionesBean)contexto.get("resultadoCertificacion");
		W83bUsuarioXLNetsBean usuario = (W83bUsuarioXLNetsBean)contexto.get(W83bClsConstantes.CONSTANTE_CONTEXTO_USUARIO);
		//cabecera
		HashMap datosDelDep=  W83bUtilidadesComunes.obtenerTitulosDelegacionDepartamento(usuario,certificacion.getIdioma());
	    StringBuffer  tituloDelelegacionEu = (StringBuffer)datosDelDep.get("tituloDelelegacionEu");
		StringBuffer  tituloDelelegacionEs = (StringBuffer)datosDelDep.get("tituloDelelegacionEs");
		StringBuffer  tituloDepEu = (StringBuffer)datosDelDep.get("tituloDepEu");
		StringBuffer  tituloDepEs = (StringBuffer)datosDelDep.get("tituloDepEs");
	    mapaPar.put("<<DEPCAS>>",tituloDepEs.toString());
	    mapaPar.put("<<DEPEUS>>",tituloDepEu.toString());
	    mapaPar.put("<<DELEGACION>>",tituloDelelegacionEs.toString());
	    mapaPar.put("<<DELEGACIONEUSK>>",tituloDelelegacionEu.toString());
	    //fin de cabecera
	    //PIE
	   mapaPar.put("<<PIE>>",usuario.getCalleListadosFormateada());
	    //FIN PIE
	   String[] firmante = certificacion.getFirmante().split("_");
	   
	   String auxSC=W83bClsConstantes.VACIO;
		String auxSCEusk=W83bClsConstantes.VACIO;
		if(W83bClsConstantes.CONSTANTE_SERVICIOS_CENTRALES.equals(certificacion.getUsuarioBean().getCodTerritorioDelegacion()))
				{
					auxSCEusk="LAN ";
					auxSC=" DE TRABAJO";
				}
		mapaPar.put("<<RESPONSABLE>>",firmante[0].toUpperCase());
		mapaPar.put("<<CARGO>>",certificacion.getCargodesc().toUpperCase().concat(auxSC));
		mapaPar.put("<<CARGOEU>>",auxSCEusk.concat(certificacion.getCargodese().toUpperCase()));
		
		
		
		mapaPar.put("<<RAZONSOCIAL>>",certificacion.getRazon());
		mapaPar.put("<<RAZONSOCIALEUSK>>",certificacion.getRazon());
		
		mapaPar.put("<<LOC>>",usuario.getLocalidadTxtCastDelegacion());
		mapaPar.put("<<LOCEUSK>>",usuario.getLocalidadTxtEuskDelegacion());
		
		SimpleDateFormat sdf =new SimpleDateFormat(W83bDateUtil.ES_PATTERN);
		List listaDia = W83bDateUtil.getInstance().separarDiaMesAnyo(sdf.format(new Date()),W83bClsConstantes.CONSTANTE_CASTELLANO);
		int miMesCas = Integer.parseInt((String)listaDia.get(1)) -1 ;			
		String mesCastellano = W83bDateUtil.getInstance().sabernombremesmin(miMesCas, W83bClsConstantes.CONSTANTE_CASTELLANO);
		mapaPar.put("<<FECCAS>>",listaDia.get(0)+" de " + mesCastellano + " de " + listaDia.get(2));
		
		sdf =new SimpleDateFormat(W83bDateUtil.ES_PATTERN);
		List listaDiaEusk = W83bDateUtil.getInstance().separarDiaMesAnyo(sdf.format(new Date()),W83bClsConstantes.CONSTANTE_EUSKARA);
		int miMesEus = Integer.parseInt((String)listaDiaEusk.get(1)) -1;
		String mesEuskera = W83bDateUtil.getInstance().sabernombremesmin(miMesEus, W83bClsConstantes.CONSTANTE_EUSKARA);
		mapaPar.put("<<FECUSK>>",listaDiaEusk.get(0)+"(e)ko " + mesEuskera + "(a)ren " + listaDiaEusk.get(2)+"(e)(a)n");
		
		listaDia = W83bDateUtil.getInstance().separarDiaMesAnyo(W83bDateUtil.getInstance().getLocaleStringFromDate(W83bDateUtil.getInstance().stringToDateIdioma(certificacion.getFechaResultado(),certificacion.getIdioma()), W83bClsConstantes.CONSTANTE_CASTELLANO),W83bClsConstantes.CONSTANTE_CASTELLANO);
		listaDiaEusk = W83bDateUtil.getInstance().separarDiaMesAnyo(W83bDateUtil.getInstance().getLocaleStringFromDate(W83bDateUtil.getInstance().stringToDateIdioma(certificacion.getFechaResultado(),certificacion.getIdioma()), W83bClsConstantes.CONSTANTE_CASTELLANO),W83bClsConstantes.CONSTANTE_EUSKARA);
		
		
		miMesCas = Integer.parseInt((String)listaDia.get(1)) -1 ;
		miMesEus = Integer.parseInt((String)listaDiaEusk.get(1)) -1;
		
		mesCastellano = W83bDateUtil.getInstance().sabernombremesmin(miMesCas, W83bClsConstantes.CONSTANTE_CASTELLANO);
		mesEuskera = W83bDateUtil.getInstance().sabernombremesmin(miMesEus, W83bClsConstantes.CONSTANTE_EUSKARA);
		
		mapaPar.put("<<FECHARESULT>>",listaDia.get(0)+" de " + mesCastellano + " de " + listaDia.get(2));
		mapaPar.put("<<FECHARESULTEUSK>>",listaDiaEusk.get(0)+"(e)ko " + mesEuskera + "(a)ren " + listaDiaEusk.get(2) + "(e)(a)n");
		
		String sector="";
	   	W83bCertificacionesBean cert=new W83bCertificacionesBean();
	   	List lista=certificacion.getListaSindicatos();
	   	StringBuffer tabla= new StringBuffer(5000);
	   	int i=0;
	   	String sindicato="";
	   	int contadorSectores=1;
	   	while(i<lista.size()&&tabla.length()<2500000){
			cert=(W83bCertificacionesBean)lista.get(i);
			if(StringUtils.isEmpty(cert.getSector()))
			{
					cert.setSector(Q70GestorMensajesi18n.getSingleton().getMessage("w83bcomun","comun.actas.totales",certificacion.getIdioma()).toUpperCase());
					cert.setDescSector(Q70GestorMensajesi18n.getSingleton().getMessage("w83bcomun","comun.actas.totales",certificacion.getIdioma()).toUpperCase());
			}
			if(certificacion.getIdioma().equals(W83bClsConstantes.CONSTANTE_CASTELLANO)){
				sindicato=cert.getDescripcionSindicato();
			}
			else{
				sindicato=cert.getDescripcionSindicatoEusk();
			}
			if(i==0){
				sector=cert.getSector();
				//empezar tabla
				tabla=empezarTabla(tabla,String.valueOf(contadorSectores),cert.getDescSector(),certificacion.getIdioma());
				//poner la fila
				tabla=meterLinea(tabla,sindicato,cert.getDelegados(),calcularporcentaje(Integer.parseInt(cert.getDelegados()),Integer.parseInt((cert.getTotal()))));
			}
			else if(!sector.equalsIgnoreCase(cert.getSector())){
				contadorSectores++;
				//terminamos la tabla
				tabla=finalizarTabla(tabla);
				tabla.append("{\\\\rtlch\\\\fcs1 \\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\b\\\\insrsid15423775 \\\\page }");
				sector=cert.getSector();
			   	//empezar tabla
			   	tabla=empezarTabla(tabla,String.valueOf(contadorSectores),cert.getDescSector(),certificacion.getIdioma());
				//poner la fila
			   	tabla=meterLinea(tabla,sindicato,cert.getDelegados(),calcularporcentaje(Integer.parseInt(cert.getDelegados()),Integer.parseInt((cert.getTotal()))));
			}
			else if(sector.equalsIgnoreCase(cert.getSector())){
				//poner la fila
				tabla=meterLinea(tabla,sindicato,cert.getDelegados(),calcularporcentaje(Integer.parseInt(cert.getDelegados()),Integer.parseInt((cert.getTotal()))));
			}
			i++;
			//el titulo
		}
	  //terminamos la tabla
	   	tabla=finalizarTabla(tabla);
	   	
	   	
	mapaPar.put("<<TABLA>>", tabla.toString());			
	if(tabla.length()>=2500000){
		contexto.set(W83bClsConstantes.CONSTANTE_MENSAJES_APLICACION_NO_ERROR, "comun.mensaje.noTantosConvenios");
		contexto.get("w83bCertificacionesBean");
		return mapping.findForward("ok");
		
	}	
	StringBuffer buffer = W83bUtilidadesRTF.sustituirCadenaCaracteresRtf(plantilla.getFichero(), mapaPar);
		
	
    response.setContentType("application/msword");
    response.setContentLength(buffer.toString().getBytes().length);
    response.setHeader("Content-disposition","attachment;filename="+plantilla.getNombrePlantilla());
    response.getOutputStream().write(buffer.toString().getBytes());
    response.getOutputStream().flush();
	
    return null;
	}
	private StringBuffer empezarTabla(StringBuffer tabla,String contador,String titulo,String idioma) {
			tabla.append("{\\\\rtlch\\\\fcs1 \\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\b\\\\insrsid16012776 ");
			tabla.append(contador);
			tabla.append(".- ");
			try{
				 if(Q70GestorMensajesi18n.getSingleton().getMessage("w83bcomun","comun.actas.totales",idioma).toUpperCase().equals(titulo))
				 {
						tabla.append(titulo);
						
				 }else{
						tabla.append(Q70GestorMensajesi18n.getSingleton().getMessage("w83bcomun","comun.centroTrabajo.sector",idioma)).append(" ").append(titulo);
						
				 }
			}
			catch(Exception e){}
			tabla.append("}{\\\\rtlch\\\\fcs1 \\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\insrsid14778100 }{\\\\rtlch\\\\fcs1 \\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\insrsid4657642\\\\charrsid4657642 ");
			tabla.append("\\\\par \\\\par \\\\ltrrow}\\\\trowd \\\\irow0\\\\irowband0\\\\ltrrow\\\\");
			tabla.append("ts11\\\\trqc\\\\trgaph70\\\\trrh300\\\\trleft-1567\\\\trkeep\\\\trftsWidth3\\\\trwWidth8349\\\\trftsWidthB3\\\\trftsWidthA3\\\\trautofit1\\\\trpaddl70\\\\trpaddr70\\\\trpaddfl3\\\\trpaddft3\\\\trpaddfb3\\\\trpaddfr3\\\\tblrsid11612192\\\\tblind-1497\\\\tblindtype3"); 
			tabla.append("\\\\clvertalb\\\\clbrdrt\\\\brdrs\\\\brdrw20 \\\\clbrdrl\\\\brdrs\\\\brdrw20 \\\\clbrdrb\\\\brdrs\\\\brdrw10 \\\\clbrdrr\\\\brdrs\\\\brdrw10 \\\\cltxlrtb\\\\clNoWrap\\\\clftsWidth3\\\\clwWidth4742\\\\clshdrawnil \\\\cellx3175\\\\clvertalb\\\\clbrdrt\\\\brdrs\\\\brdrw20 \\\\clbrdrl\\\\brdrnone \\\\clbrdrb\\\\brdrs\\\\brdrw10 \\\\clbrdrr");
			tabla.append("\\\\brdrs\\\\brdrw10 \\\\cltxlrtb\\\\clNoWrap\\\\clftsWidth3\\\\clwWidth1843\\\\clshdrawnil \\\\cellx5018\\\\clvertalb\\\\clbrdrt\\\\brdrs\\\\brdrw20 \\\\clbrdrl\\\\brdrnone \\\\clbrdrb\\\\brdrs\\\\brdrw10 \\\\clbrdrr\\\\brdrs\\\\brdrw10 \\\\cltxlrtb\\\\clNoWrap\\\\clftsWidth3\\\\clwWidth1764\\\\clshdrawnil \\\\cellx6782");
			tabla.append("\\\\pard \\\\ltrpar\\\\qc \\\\li0\\\\ri0\\\\widctlpar\\\\intbl\\\\wrapdefault\\\\aspalpha\\\\aspnum\\\\faauto\\\\adjustright\\\\rin0\\\\lin0\\\\pararsid11612192 {\\\\rtlch\\\\fcs1 \\\\ai\\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\b\\\\insrsid11612192 SINDIKATUA");
			tabla.append("\\\\par CENTRAL SINDICAL}{\\\\rtlch\\\\fcs1 \\\\ai\\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\b\\\\insrsid11612192\\\\charrsid4657642 \\\\cell }\\\\pard \\\\ltrpar\\\\qc \\\\li0\\\\ri0\\\\widctlpar\\\\intbl\\\\wrapdefault\\\\aspalpha\\\\aspnum\\\\faauto\\\\adjustright\\\\rin0\\\\lin0\\\\pararsid7743554 {\\\\rtlch\\\\fcs1 \\\\ai\\\\af1\\\\afs22"); 
			tabla.append("\\\\ltrch\\\\fcs0 \\\\b\\\\insrsid11612192 ORDEZKARIAK");
			tabla.append("\\\\par DELEGADOS}{\\\\rtlch\\\\fcs1 \\\\ai\\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\b\\\\insrsid11612192\\\\charrsid4657642 \\\\cell }{\\\\rtlch\\\\fcs1 \\\\ai\\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\b\\\\insrsid11612192 %}{\\\\rtlch\\\\fcs1 \\\\ai\\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\b\\\\insrsid11612192\\\\charrsid4657642"); 
			tabla.append("\\\\~\\\\cell }\\\\pard \\\\ltrpar\\\\ql \\\\li0\\\\ri0\\\\widctlpar\\\\intbl\\\\wrapdefault\\\\aspalpha\\\\aspnum\\\\faauto\\\\adjustright\\\\rin0\\\\lin0 {\\\\rtlch\\\\fcs1 \\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\insrsid11612192\\\\charrsid4657642 \\\\trowd \\\\irow0\\\\irowband0\\\\ltrrow\\\\");
			
			return tabla;
	}
	private StringBuffer meterLinea(StringBuffer tabla,String sindicato,String delegados,String porcentaje){
		tabla.append("ts11\\\\trqc\\\\trgaph70\\\\trrh300\\\\trleft-1567\\\\trkeep\\\\trftsWidth3\\\\trwWidth8349\\\\trftsWidthB3\\\\trftsWidthA3\\\\trautofit1\\\\trpaddl70\\\\trpaddr70\\\\trpaddfl3\\\\trpaddft3\\\\trpaddfb3\\\\trpaddfr3\\\\tblrsid11612192\\\\tblind-1497\\\\tblindtype3 \\\\clvertalb\\\\clbrdrt\\\\brdrs\\\\brdrw20 \\\\clbrdrl");
		tabla.append("\\\\brdrs\\\\brdrw20 \\\\clbrdrb\\\\brdrs\\\\brdrw10 \\\\clbrdrr\\\\brdrs\\\\brdrw10 \\\\cltxlrtb\\\\clNoWrap\\\\clftsWidth3\\\\clwWidth4742\\\\clshdrawnil \\\\cellx3175\\\\clvertalb\\\\clbrdrt\\\\brdrs\\\\brdrw20 \\\\clbrdrl\\\\brdrnone \\\\clbrdrb\\\\brdrs\\\\brdrw10 \\\\clbrdrr\\\\brdrs\\\\brdrw10 ");
		tabla.append("\\\\cltxlrtb\\\\clNoWrap\\\\clftsWidth3\\\\clwWidth1843\\\\clshdrawnil \\\\cellx5018\\\\clvertalb\\\\clbrdrt\\\\brdrs\\\\brdrw20 \\\\clbrdrl\\\\brdrnone \\\\clbrdrb\\\\brdrs\\\\brdrw10 \\\\clbrdrr\\\\brdrs\\\\brdrw10 \\\\cltxlrtb\\\\clNoWrap\\\\clftsWidth3\\\\clwWidth1764\\\\clshdrawnil \\\\cellx6782\\\\row \\\\ltrrow}\\\\pard \\\\ltrpar");
		tabla.append("\\\\ql \\\\li0\\\\ri0\\\\widctlpar\\\\intbl\\\\wrapdefault\\\\aspalpha\\\\aspnum\\\\faauto\\\\adjustright\\\\rin0\\\\lin0\\\\pararsid7743554 {\\\\rtlch\\\\fcs1 \\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\insrsid11612192 ");
		tabla.append(sindicato);
		tabla.append("}{\\\\rtlch\\\\fcs1 \\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 ");
		tabla.append("\\\\insrsid11612192\\\\charrsid4657642 \\\\cell }\\\\pard \\\\ltrpar\\\\qc \\\\li0\\\\ri0\\\\widctlpar\\\\intbl\\\\wrapdefault\\\\aspalpha\\\\aspnum\\\\faauto\\\\adjustright\\\\rin0\\\\lin0\\\\pararsid11612192 {\\\\rtlch\\\\fcs1 \\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\insrsid11612192 ");
		tabla.append(delegados);
		tabla.append("\\\\cell ");
		tabla.append(porcentaje);
		tabla.append("%");
		tabla.append("\\\\cell }\\\\pard \\\\ltrpar\\\\ql \\\\li0\\\\ri0\\\\widctlpar\\\\intbl\\\\wrapdefault\\\\aspalpha\\\\aspnum\\\\faauto\\\\adjustright\\\\rin0\\\\lin0 {\\\\rtlch\\\\fcs1 \\\\af1\\\\afs22 \\\\ltrch\\\\fcs0 \\\\insrsid11612192\\\\charrsid4657642 \\\\trowd \\\\irow1\\\\irowband1\\\\lastrow \\\\ltrrow\\\\");
		return tabla;
	}
	private StringBuffer finalizarTabla(StringBuffer tabla){
		tabla.append("ts11\\\\trqc\\\\trgaph70\\\\trrh300\\\\trleft-1567\\\\trkeep\\\\trftsWidth3\\\\trwWidth8349\\\\trftsWidthB3\\\\trftsWidthA3\\\\trautofit1\\\\trpaddl70\\\\trpaddr70\\\\trpaddfl3\\\\trpaddft3\\\\trpaddfb3\\\\trpaddfr3\\\\tblrsid11612192\\\\tblind-1497\\\\tblindtype3 \\\\clvertalb\\\\clbrdrt\\\\brdrs\\\\brdrw20 \\\\clbrdrl");
		tabla.append("\\\\brdrs\\\\brdrw20 \\\\clbrdrb\\\\brdrs\\\\brdrw10 \\\\clbrdrr\\\\brdrs\\\\brdrw10 \\\\cltxlrtb\\\\clNoWrap\\\\clftsWidth3\\\\clwWidth4742\\\\clshdrawnil \\\\cellx3175\\\\clvertalb\\\\clbrdrt\\\\brdrs\\\\brdrw20 \\\\clbrdrl\\\\brdrnone \\\\clbrdrb\\\\brdrs\\\\brdrw10 \\\\clbrdrr\\\\brdrs\\\\brdrw10 ");
		tabla.append("\\\\cltxlrtb\\\\clNoWrap\\\\clftsWidth3\\\\clwWidth1843\\\\clshdrawnil \\\\cellx5018\\\\clvertalb\\\\clbrdrt\\\\brdrs\\\\brdrw20 \\\\clbrdrl\\\\brdrnone \\\\clbrdrb\\\\brdrs\\\\brdrw10 \\\\clbrdrr\\\\brdrs\\\\brdrw10 \\\\cltxlrtb\\\\clNoWrap\\\\clftsWidth3\\\\clwWidth1764\\\\clshdrawnil \\\\cellx6782\\\\row }\\\\pard \\\\ltrpar");
		tabla.append("\\\\ql \\\\li0\\\\ri0\\\\widctlpar\\\\wrapdefault\\\\aspalpha\\\\aspnum\\\\faauto\\\\adjustright\\\\rin0\\\\lin0\\\\itap0\\\\pararsid4657642 ");
		return tabla;
	}
	private String calcularporcentaje(int totalparc,int total){
		DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
		simbolos.setDecimalSeparator(',');
		DecimalFormat formateador = new DecimalFormat("####.##",simbolos);
		if (total==0){
			return "0";
		}
		else{
			float n=((float)totalparc*100)/(float)total;
			return formateador.format(n);
		}
	}
}

